package com.banciyuan.bcywebview.biz.post.write;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.base.view.listview.NoScrollListView;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.daoexample.model.Character;
import de.greenrobot.daoexample.model.PostItem;

/**
 * Created by hy on 2016/1/5.
 */
public class WriteInfoActivity extends BaseActivity implements View.OnClickListener, ActionbarHelper.OnActionCallbacks {
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private EditText et_intro;
    private EditText et_tags;
    private FlowView tag_area;
    private FlowView re_tags_area;
    private TextView tv_add_tag;
    private LinearLayout draw_warn;
    private PostItem postItem;
    private PostItem.Optional optional;

    private String history;
    private LinearLayout rl_add_character;
    private List<Character> clist = new ArrayList<Character>();
    private WriteCharacterAdapter writeCharacterAdapter;
    private NoScrollListView noScrollListView;
    private ShowAdd showAdd;
    private RequestQueue queue;

    private boolean operation_flag = false;
    private boolean show_tags = true;
    private Set<String> mTagSet = new LinkedHashSet<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_info_set);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        getTagFromDiskMemory();
        initData();
        getState();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        Gson gson = new Gson();
        postItem = (PostItem) getIntent().getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        show_tags = getIntent().getBooleanExtra(gotoUtil.INTENT_VALUE_TWO, true);
        history = gson.toJson(postItem.getOptional());
        optional = postItem.getOptional();
    }

    private void getTagFromDiskMemory() {
        Gson gson = new Gson();
        String tagStr = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.WRITETAG, "[]");
        mTagSet = gson.fromJson(tagStr, new TypeToken<LinkedHashSet<String>>() {
        }.getType());
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.add_more_info));
        mActionbarHelper.setActionCallbacks(this);
    }

    @Override
    protected void initUi() {
        et_intro = (EditText) findViewById(R.id.et_intro);
        et_intro.setHint(getString(R.string.write_saysomething));
        et_tags = (EditText) findViewById(R.id.et_tags);
        tag_area = (FlowView) findViewById(R.id.tag_area);
        re_tags_area = (FlowView) findViewById(R.id.re_tags_area);
        tv_add_tag = (TextView) findViewById(R.id.tag_group_add);
        draw_warn = (LinearLayout) findViewById(R.id.draw_warn);
        draw_warn.setVisibility(View.GONE);
        findViewById(R.id.ll_title_intro).setVisibility(View.GONE);
        findViewById(R.id.title_intro_line).setVisibility(View.GONE);
        TextView recommend_tv = (TextView) findViewById(R.id.write_warn);
        recommend_tv.setVisibility(View.VISIBLE);
        recommend_tv.setText(Html.fromHtml(getString(R.string.cp_copy_warn) + getString(R.string.pink_cp_copy) + getString(R.string.cp_detail_tag)));
        rl_add_character = (LinearLayout) findViewById(R.id.rl_add_character);
        if (postItem.getType().equals(WritePostActivity.dongjin)) {
            findViewById(R.id.ll_character).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.ll_character).setVisibility(View.GONE);
        }
        noScrollListView = (NoScrollListView) findViewById(R.id.lv_character);
        if (!show_tags) {
            findViewById(R.id.tag_main).setVisibility(View.GONE);
        }

    }

    public interface ShowAdd {
        void show();
    }

    private void getState() {
        if (!TextUtils.isEmpty(optional.getIntro())) {
            et_intro.setText(optional.getIntro());
        }
        if (optional.getTags() != null && !optional.getTags().isEmpty()) {
            tag_area.removeAllViews();
            if (tag_area.getVisibility() == View.GONE) tag_area.setVisibility(View.VISIBLE);
            for (String s : optional.getTags()) {
                addTagView(s);
            }
        }
        if (optional.getCharacter() != null) {
            if (!optional.getCharacter().isEmpty()) {
                writeCharacterAdapter = new WriteCharacterAdapter(optional.getCharacter(), this, showAdd);
            } else {
                optional.getCharacter().add("");
                writeCharacterAdapter = new WriteCharacterAdapter(optional.getCharacter(), this, showAdd);
            }
        } else {
            optional.setCharacter(new ArrayList<String>());
            optional.getCharacter().add("");
            writeCharacterAdapter = new WriteCharacterAdapter(optional.getCharacter(), this, showAdd);
        }
        noScrollListView.setAdapter(writeCharacterAdapter);
    }

    @Override
    protected void initAction() {
        tv_add_tag.setOnClickListener(this);
        rl_add_character.setOnClickListener(this);
        showAdd = new ShowAdd() {
            @Override
            public void show() {
                rl_add_character.setVisibility(View.VISIBLE);
                saveCharacter();
            }
        };
        et_tags.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    addTag(et_tags.getText().toString());
                }
                return true;
            }
        });
    }


    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + NovelApi.getRecommendtags();
        List<BcyPair> param = new ArrayList<BcyPair>();
        param.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        param.add(new BcyPair(HttpUtils.TYPE, postItem.getType()));
        Map<String, String> map = HttpUtils.getData(param);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, WriteInfoActivity.this)) {
                    re_tags_area.setVisibility(View.VISIBLE);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        Gson gson = new Gson();
                        List<String> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<String>>() {
                        }.getType());
                        mTagSet.addAll(templist);
                        for (final String name : mTagSet) {
                            View tags = View.inflate(WriteInfoActivity.this, R.layout.tag_nomargin_blue, null);
                            TextView tv = (TextView) tags.findViewById(R.id.single_tag);
                            tv.setText(name);
                            tags.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    addTag(name);
                                }
                            });
                            re_tags_area.addView(tags);
                        }
                    } catch (JSONException e) {
                        re_tags_area.setVisibility(View.GONE);
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                re_tags_area.setVisibility(View.GONE);
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(stringRequestParam);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tag_group_add:
                addTag(et_tags.getText().toString());
                break;
            case R.id.rl_add_character:
                addCharater();
                break;
        }
    }

    private void addCharater() {
        saveCharacter();
        if (optional.getCharacter() != null) {
            if (optional.getCharacter().size() < 10) {
                optional.getCharacter().add("");
                writeCharacterAdapter.changeFlag();
                writeCharacterAdapter.notifyDataSetChanged();
                if (optional.getCharacter().size() >= 10) {
                    rl_add_character.setVisibility(View.GONE);
                }
            } else {
                MyToast.show(this, getString(R.string.over_ten));
            }
        }
    }

    private void saveCharacter() {
        for (int i = 0; i < noScrollListView.getChildCount(); i++) {
            View view = noScrollListView.getChildAt(i);
            TextView tv1 = (TextView) view.findViewById(R.id.character_mname);
            if (optional.getCharacter() != null) {
                optional.getCharacter().set(i, tv1.getText().toString());
            }
        }
    }

    private void addTag(String name) {
        if (optional.getTags().size() < 5) {
            if (!operation_flag) {
                operation_flag = true;
                if (!TextUtils.isEmpty(name)) {
                    if (name.equals(postItem.getWork())) {
                        MyToast.show(this, getString(R.string.tag_work_cannot_repeat));
                        operation_flag = false;
                        return;
                    }
                    for (int i = 0; i < noScrollListView.getChildCount(); i++) {
                        View view = noScrollListView.getChildAt(i);
                        TextView tv = (TextView) view.findViewById(R.id.character_mname);
                        if (name.equals(tv.getText().toString())) {
                            MyToast.show(this, getString(R.string.tag_role_cannot_repeat));
                            operation_flag = false;
                            return;
                        }
                    }
                    if (tag_area.getVisibility() == View.GONE) tag_area.setVisibility(View.VISIBLE);
                    for (int i = 0; i < optional.getTags().size(); i++) {
                        if (optional.getTags().get(i).equals(name)) {
                            MyToast.show(this, getString(R.string.tag_not_equal));
                            operation_flag = false;
                            return;
                        }
                    }
                    addTagView(name);
                    optional.getTags().add(name);
                    et_tags.setText("");
                } else {
                    MyToast.show(this, getString(R.string.tag_not_null));
                }
                operation_flag = false;
            }
        } else {
            MyToast.show(this, getString(R.string.label_five_limit));
        }
    }

    private void addTagView(final String name) {
        final View tag = View.inflate(this, R.layout.tag_blue_cancel, null);
        TextView tv_name = (TextView) tag.findViewById(R.id.single_tag_cancel);
        tv_name.setText(name);
        tag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tag_area.removeView(tag);
                if (!operation_flag) {
                    operation_flag = true;
                    optional.getTags().remove(name);
                    operation_flag = false;
                }
                if (tag_area.getChildCount() == 0) {
                    tag_area.setVisibility(View.GONE);
                }
            }
        });
        tag_area.addView(tag);
    }

    @Override
    public void onBackPressed() {
        finishActvitiy();
        super.onBackPressed();
    }

    private void finishActvitiy() {
        if (et_intro.getText() != null) {
            optional.setIntro(et_intro.getText().toString());
        }
        List<String> templist = new ArrayList<String>();
        for (int i = 0; i < noScrollListView.getChildCount(); i++) {
            View view = noScrollListView.getChildAt(i);
            TextView tv = (TextView) view.findViewById(R.id.character_mname);
            String name = null;
            if (!TextUtils.isEmpty(name = tv.getText().toString())) {
                templist.add(name);
            } else {
                continue;
            }
        }
        optional.setCharacter(templist);
        postItem.setOptional(optional);
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(et_intro.getText())
                || (optional.getCharacter() != null && !optional.getCharacter().isEmpty())
                || (optional.getTags() != null && !optional.getTags().isEmpty())) {
            intent.putExtra("change", true);
        } else {
            intent.putExtra("change", false);
        }
        intent.putExtra("postitem", postItem);
        setResult(WritePostActivity.GO_SETINFO, intent);
    }


    @Override
    public void onBackClick() {
        finishActvitiy();
        finish();
    }

    @Override
    public void onActionClick(int id) {

    }
}
